package com.baike.service.impl;

import com.baike.entity.TbLessonCatalogue;
import com.baike.mapper.TbLessonCatalogueMapper;
import com.baike.service.ITbLessonCatalogueService;
import com.baike.vo.CatalogueVoClass;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lbs
 * @since 2021-10-31
 */
@Service
public class TbLessonCatalogueServiceImpl extends ServiceImpl<TbLessonCatalogueMapper, TbLessonCatalogue> implements ITbLessonCatalogueService {


    // 根据课程id 获取课程整个目录
    public List<CatalogueVoClass> findCatalogueByLessonId(Long lessonId) {
        // 根据课程id 获取所有目录条数
        LambdaQueryWrapper<TbLessonCatalogue> wrapper = Wrappers.<TbLessonCatalogue>lambdaQuery().eq(TbLessonCatalogue::getLessonId, lessonId);
        List<TbLessonCatalogue> list = list(wrapper);
        List<CatalogueVoClass> catalogueTreeList = getCatalogueTreeList(list,0L);
        return catalogueTreeList;

    }

    private List<CatalogueVoClass> getCatalogueTreeList(List<TbLessonCatalogue> list, Long id) {
        //定义集合拼接后的数据
        List<CatalogueVoClass> catalogueTreeList = new ArrayList<>();
        //拼接数据 循环所有数据库查到的数据
        for(TbLessonCatalogue catalogue : list){
            // 定义map 接收数据
            CatalogueVoClass catalogueVo = null;
            // 判断父级Id是否有等于当前id的 相等就证明是他的子级 把这条数据放到map中
            if(catalogue.getPid().equals(id)){
                catalogueVo = new CatalogueVoClass();
                catalogueVo.setId(catalogue.getId());
                catalogueVo.setCatalogueName(catalogue.getCatalogueName());
                catalogueVo.setPid(catalogue.getPid());
                catalogueVo.setVideoUrl(catalogue.getVideoUrl());
                catalogueVo.setLessonId(catalogue.getLessonId());
                catalogueVo.setVideoLength(catalogue.getVideoLength());
                catalogueVo.setChildrenList(getCatalogueTreeList(list,catalogue.getId()));
            }
            // 如果 这次循环取到了数据 就把map 放到集合中
            if(catalogueVo != null){
                // 如果子节点没有数据 删除子节点
                List<CatalogueVoClass>  childrenList = (List<CatalogueVoClass>)catalogueVo.getChildrenList();
                if(childrenList.size() < 1){
                    catalogueVo.setChildrenList(null);
                }
                catalogueTreeList.add(catalogueVo);
            }
        }
        return catalogueTreeList;

    }
}
